#include <IUCompress.h>

#include "datastream.h"
#include "RXTypes.h"

struct OutputData
{
	uint8_t tupleSize;
	IUImage::ScalarType scalarType;
	uint32_t width;
	uint32_t height;
	uint8_t data[0];
};

DataOutputStream & operator<<(DataOutputStream & s, const Image & r)
{
	if (!r.IsNull())
	{
		ByteArray buffer;
		
		int size = r.GetDataSize() + sizeof(OutputData);
		buffer.resize(size);
		OutputData* data = (OutputData*)buffer.data();
		
		data->width = r.GetSize()[0];
		data->height = r.GetSize()[1];
		data->tupleSize = r.GetTupleSize();
		data->scalarType = r.GetScalarType();
		memcpy(data->data, r.GetData(), r.GetDataSize());

		buffer = IUCompress::Compress(buffer);

		s << true;
		s << buffer;
	}
	else {
		s << false;
	}

	return s;
}

DataInputStream & operator>>(DataInputStream & s, Image & r)
{
	bool valid;

	s >> valid;

	if (valid)
	{
		ByteArray buffer;
		s >> buffer;
		IUCompress::UnCompressError err;
		buffer = IUCompress::Uncompress(buffer, &err);
		if (err != IUCompress::UE_OK)
		{
			throw ParseException("InputStream Image Error:Uncompress Data Failed !");
		}
		OutputData* data = (OutputData*)buffer.data();
		r = Image(data->scalarType, data->tupleSize, Size2I(data->width, data->height));

		memcpy(r.GetData(), data->data, r.GetDataSize());
	}
	else
	{
		r = Image();
	}
	return s;
}